package com.smartfast4j.backend.modules.sys.security.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.smartfast4j.backend.common.bean.R;
import com.smartfast4j.backend.common.util.ShiroUtils;
import com.smartfast4j.backend.common.util.WebUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Map;

/**
 * 自定义Shiro 登录拦截器
 * AccessControlFilter提供了访问控制的基础功能；比如是否允许访问/当访问拒绝时如何处理等
 * 想进行访问访问的控制就可以继承AccessControlFilter
 * Created by gacl on 2017/9/9.
 */
public class LoginFilter extends AccessControlFilter {

    private static final Logger logger = Logger.getLogger(LoginFilter.class);

    /**
     * 是否允许访问，返回true表示允许
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        logger.debug("进入LoginFilter→isAccessAllowed方法处理用户请求，isAjaxRequest="+ShiroFilterUtils.isAjax(servletRequest));
        Map<String, String> params = WebUtil.getRequestParams(servletRequest);
        logger.debug("进入LoginFilter→isAccessAllowed方法处理用户请求，params="+ JSON.toJSONString(params));
        logger.info("isLoginRequest="+isLoginRequest(servletRequest,servletResponse));
        if(ShiroUtils.isLogin() || isLoginRequest(servletRequest,servletResponse)){
            return true;//返回true之后就会继续往下执行，不会进入onAccessDenied方法
        }
        return false;//返回false之后就会进入onAccessDenied
    }

    /**
     * 表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；如果返回false表示该拦截器实例已经处理了，将直接返回即可。
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        logger.debug("进入LoginFilter→onAccessDenied方法处理用户请求，isAjaxRequest="+ShiroFilterUtils.isAjax(servletRequest));
        if(ShiroFilterUtils.isAjax(servletRequest)){
            ShiroFilterUtils.out(servletResponse);
        }else{
            ShiroFilterUtils.out(servletResponse, R.error(-1,"登录已经失效，请重新登录"));
        }
        return false;
    }
}
